import java.util.ArrayList;
import java.util.List;

public class SpiralOrder {
    // leetcode 螺旋矩阵
    // https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
    public List<Integer> spiralOrder(int[][] matrix) {
        int xl = 0, xr = matrix[0].length - 1, yt = 0, yb = matrix.length - 1;
        List<Integer> ret = new ArrayList<>();
        while (true) {
            for (int j = xl; j <= xr; j++) {
                ret.add(matrix[yt][j]);
            }
            yt++;
            if (yt > yb) break;
            for (int i = yt; i <= yb; i++) {
                ret.add(matrix[i][xr]);
            }
            xr--;
            if (xl > xr) break;
            for (int j = xr; j >= xl; j--) {
                ret.add(matrix[yb][j]);
            }
            yb--;
            if (yt > yb) break;
            for (int i = yb; i >= yt; i--) {
                ret.add(matrix[i][xl]);
            }
            xl++;
            if (xl > xr) break;
        }
        return ret;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}};
        SpiralOrder spiralOrder = new SpiralOrder();
        System.out.println(spiralOrder.spiralOrder(matrix));
    }
}
